package handler

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"zg3/day13/api/request"
	"zg3/day13/internal/dao"
	"zg3/day13/internal/model"
)

func AddDynamic(c *gin.Context) {
	var req request.AddDynamic
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	dynamic := model.UserDynamic{
		UserId:  c.GetUint("userId"),
		Content: req.Content,
		Types:   req.Types,
		Likes:   0,
	}
	dao.Create(&dynamic)
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "发布动态成功",
		"data": dynamic,
	})
	return
}

func DynamicLike(c *gin.Context) {
	var req request.DynamicLike
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	var dynamic model.UserDynamic
	dao.FindId(req.DynamicId, &dynamic)
	if dynamic.Id == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "该动态不存在",
			"data": false,
		})
		return
	}

	var likes model.DynamicLike
	dao.ConditionQuery(&model.DynamicLike{
		DynamicId: req.DynamicId,
	}, &likes)
	if likes.Id != 0 {
		dao.Deleted(&likes)
		dynamic.Likes -= 1
		dao.Update(&dynamic)
		c.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  "取消点赞成功",
			"data": true,
		})
		return
	}

	dynamic.Likes += 1
	dao.Update(&dynamic)

	like := model.DynamicLike{
		DynamicId:  req.DynamicId,
		LikeUserId: c.GetUint("userId"),
	}

	dao.Create(&like)
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "动态点赞成功",
		"data": like,
	})
	return
}
